package com.b3log.baidu.pcs.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.b3log.baidu.pcs.common.IOUtil;
import com.baidu.pcs.PcsClient;

/**
 * Servlet implementation class FileUploadService
 */
public class FileUploadService extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		try {
			String method=request.getParameter("method");
			byte [] result=null;
			if(method!=null && method.equals("getImage")){
				response.setContentType("image/jpeg");
				result=IOUtil.inputStreamToByte(new FileInputStream(new File("E://0001.jpg")));
			}else{
				response.setContentType("text/html;charset=utf-8");
				this.uploadFile(request, null);
				PcsClient client=new PcsClient();	        
				result="{\"error\": 0,\"url\" : \"FileUploadService?method=getImage\"}".getBytes();
			}
			ServletOutputStream responseOutputStream = response.getOutputStream();
			responseOutputStream.write(result);
			responseOutputStream.flush();
			responseOutputStream.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private byte[] uploadFile(HttpServletRequest request,Map<String, String> parametsMap) throws Exception {
		byte[] fileBytes=null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(1024 * 1024 * 50);
        upload.setHeaderEncoding("utf-8");
        upload.setSizeMax(1024 * 1024 * 100);
		List<FileItem> items = upload.parseRequest(request);
		Iterator itr = items.iterator();
		while (itr.hasNext()) {
			FileItem item = (FileItem) itr.next();
			if(item.isFormField()){
				//parametsMap.put(item.getFieldName(), item.getString("UTF-8"));
			}else if( item.getName() != null&& !item.getName().equals("")) {
				fileBytes = item.get();
			}
		}
		return fileBytes;
	}
}
